#include "blockqueue.h"

BlockQueue::BlockQueue(int maxSize)
    : m_maxSize(maxSize)
    , m_isClosed(false)
{
    // 确保最大容量为合理值
    if (m_maxSize <= 0) {
        m_maxSize = 1000;
    }

}


void BlockQueue::enqueue(const LogMessage&msg)
{
    QMutexLocker locker(&m_mutex);

    while(m_queue.size()>=m_maxSize&&!m_isClosed)
    {
        m_notFull.wait(&m_mutex,100);
    }
    //队列不满

    if(m_isClosed)
    {
        return;
    }

    m_queue.enqueue(msg);
    //可能会有惊群效果
      qDebug() << "日志入队成功：" << msg.content; // 新增：确认入队
    m_notEmpty.notify_all();

}

LogMessage BlockQueue::dequeue()
{
    QMutexLocker locker(&m_mutex);
    while(m_queue.isEmpty()&&!m_isClosed)
    {
        m_notEmpty.wait(&m_mutex,100);
    }
    // 如果队列已关闭且为空，返回空消息
    if (m_isClosed && m_queue.isEmpty()) {
        return LogMessage();
    }


    //这里可以取数据了
    LogMessage msg=m_queue.dequeue();

    m_notFull.notify_all();
    return msg;

}

//清理
void BlockQueue::clear()
{
    QMutexLocker locker(&m_mutex);
    m_queue.clear();
    m_notFull.notify_all();
}


int BlockQueue::size() const
{
    QMutexLocker locker(&m_mutex);
    return m_queue.size();
}

void BlockQueue::close()
{
    QMutexLocker locker(&m_mutex);
    if (m_isClosed) return;

    m_isClosed = true;
    // 唤醒所有阻塞的线程，让它们退出
    m_notEmpty.wakeAll();
    m_notFull.wakeAll();
}
